package com.xiaoyu.client.ui.fragment.main;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.adapter.forum.ForumRecyAdapter;
import com.xiaoyu.client.adapter.seek.HelpRecyAdapter;
import com.xiaoyu.client.loader.banner.BannerImageLoader;
import com.xiaoyu.client.model.HomeBean;
import com.xiaoyu.client.model.HomeBean.DataBean.*;
import com.xiaoyu.client.model.forum.ForumParam;
import com.xiaoyu.client.model.nearby.ShopParam;
import com.xiaoyu.client.model.seek.SeekParam;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.forum.ForumDetailActivity;
import com.xiaoyu.client.ui.activity.help.HelpDetailActivity;
import com.xiaoyu.client.ui.activity.home.HomeSearchActivity;
import com.xiaoyu.client.ui.activity.home.NearbyShopsActivity;
import com.xiaoyu.client.ui.activity.nearby.ShopDetailActivity;
import com.xiaoyu.client.ui.dialog.SignShareMenuPow;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.OnItemRecyClickListener;
import com.xiaoyu.commonlib.ui.adapter.AllPowerfulAdapter;
import com.xiaoyu.commonlib.utils.LongitudeAndLatitude;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.commonlib.utils.UIUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.xiaoyu.client.ui.fragment.main.MainActivity.TAB_TAG_FOR_BILLION;
import static com.xiaoyu.client.ui.fragment.main.MainActivity.TAB_TAG_FOR_HELP;
import static com.xiaoyu.client.ui.fragment.main.MainActivity.TAB_TAG_FOR_SHOP;
import static com.xiaoyu.client.ui.fragment.main.MainActivity.mTabHost;

/**
 * @author jx
 * @date 创建时间 2018/11/8
 * @Description 首页
 */
public class HomeFragment extends Fragment implements View.OnClickListener, SignShareMenuPow.IShareListener, TextView.OnEditorActionListener {
    public static final String SEEK_ID = "home_seek_id";
    private LocationClient mLocationClient = null;
    public static final String HOME_SEARCH = "home_search";
    private View mView;
    @BindView(R.id.fragment_home_scroll_layout)
    NestedScrollView mScrollView;
    @BindView(R.id.fragment_home_search_edit_layout)
    EditText mEditTxt;//搜索编辑框
    @BindView(R.id.fragment_home_signin_btn)
    ImageView mSignShare;//签到按钮

    @BindView(R.id.fragment_home_car_components_btn)
    RelativeLayout mCarAccessoriesBtn;//汽车用品
    @BindView(R.id.fragment_home_help_btn)
    RelativeLayout mHelpBtn;//求助
    @BindView(R.id.fragment_home_nearby_merchant_btn)
    RelativeLayout mNearbyBtn;//附近商家

    @BindView(R.id.fragment_home_top_banner)
    Banner mTopBanner;//顶部轮播图
    @BindView(R.id.fragment_home_midlle_banner)
    Banner mMiddleBanner;//中间轮播图

    @BindView(R.id.fragment_home_seek_recom_more_btn)
    ImageView seekMoreBtn;//"为你解忧"更多按钮
    @BindView(R.id.fragment_home_store_recom_more_btn)
    ImageView storeMoreBtn;//"为你优选"更多按钮
    @BindView(R.id.fragment_home_forum_recom_more_btn)
    ImageView forumMoreBtn;//"趣味杂谈"更多按钮

    @BindView(R.id.fragment_home_seek_recom_list_container)
    RecyclerView mSeekListView;//"为你解忧"数据列表
    @BindView(R.id.fragment_home_store_recom_list_container)
    RecyclerView mStoreListView;//"为你优选"数据列表
    @BindView(R.id.fragment_home_forum_recom_list_container)
    RecyclerView mForumListView;//"趣味杂谈"数据列表


    private List<ToplunboBean> mTopList = new ArrayList<>();//顶部轮播图图片数据
    private List<GoodslunboBean> mMiddleList = new ArrayList<>();//中间商品轮播图图片数据
    private List<SeekParam> mSeekList = new ArrayList<>();//"为你解忧"数据
    private List<ShopParam> mStoreList = new ArrayList<>();//"为你优选"数据
    private List<ForumParam> mForumList = new ArrayList<>();//"趣味杂谈"数据

    private HelpRecyAdapter mSeekAdapter;//"为你解忧"数据适配器
    private AllPowerfulAdapter mStoreAdapter;//"为你优选"数据适配器
    private ForumRecyAdapter mForumAdapter;//"趣味杂谈"数据适配器

    private String lat;//纬度
    private String lng;//经度


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_home, container, false);
            //绑定fragment
            ButterKnife.bind(this, mView);
            initView();
        }
        ViewGroup parent = (ViewGroup) mView.getParent();
        if (parent != null) {
            parent.removeView(mView);
        }
        return mView;
    }


    @Override
    public void onResume() {
        super.onResume();
        mLocationClient.start();
    }

    private void initView() {
        initBanner();
        initRecy();
        mCarAccessoriesBtn.setOnClickListener(this);
        mHelpBtn.setOnClickListener(this);
        mNearbyBtn.setOnClickListener(this);
        mSignShare.setOnClickListener(this);
        mEditTxt.setOnEditorActionListener(this);

        //更多按钮
        seekMoreBtn.setOnClickListener(this);
        storeMoreBtn.setOnClickListener(this);
        forumMoreBtn.setOnClickListener(this);

        mLocationClient = new LocationClient(getActivity().getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);
        option.setCoorType("GCJ02");
        option.setOpenGps(true);
        mLocationClient.setLocOption(option);

    }


    /**
     * 定位监听
     */
    public BDAbstractLocationListener myListener = new BDAbstractLocationListener(){
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

            lat = String.valueOf(location.getLatitude());//获取纬度信息
            lng = String.valueOf(location.getLongitude());//获取经度信息
            mLocationClient.stop();
            getHomeInfo();

        }
    };

    //初始化轮播图
    private void initBanner() {
        //顶部轮播图
        mTopBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mTopBanner.setIndicatorGravity(BannerConfig.CENTER);
        //设置是否自动轮播（不设置则默认自动）
        mTopBanner.isAutoPlay(true);
        //设置是否允许手动滑动轮播图
        mTopBanner.setViewPagerIsScroll(true);
        //设置轮播图片间隔时间（不设置默认为2000）
        mTopBanner.setDelayTime(2000);
        mTopBanner.setImageLoader(new BannerImageLoader());
        mTopBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

            }
        });


        //中间轮播图
        mMiddleBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        mMiddleBanner.setIndicatorGravity(BannerConfig.CENTER);
        //设置是否自动轮播（不设置则默认自动）
        mMiddleBanner.isAutoPlay(true);
        //设置是否允许手动滑动轮播图
        mMiddleBanner.setViewPagerIsScroll(true);
        //设置轮播图片间隔时间（不设置默认为2000）
        mMiddleBanner.setDelayTime(2000);
        mMiddleBanner.setImageLoader(new BannerImageLoader());
        mMiddleBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

            }
        });


    }


    //初始化Recy列表
    private void initRecy() {
        //为你解忧列表
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.divider_recy_gray));
        mSeekListView.addItemDecoration(divider);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mSeekListView.setLayoutManager(manager);
        mSeekAdapter = new HelpRecyAdapter(getActivity(), mSeekList);
        mSeekListView.setAdapter(mSeekAdapter);
        mSeekAdapter.setOnItemRecyClickListener(onSeekItemListener);
        mSeekListView.setNestedScrollingEnabled(false);


        //为你优选列表
        mStoreListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        setStoreAdapter(mStoreList);

        //趣味杂谈列表
        LinearLayoutManager forumManager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mForumListView.setLayoutManager(forumManager);
        mForumAdapter = new ForumRecyAdapter(getActivity(), mForumList);
        mForumListView.setAdapter(mForumAdapter);
        mForumAdapter.setOnItemRecyClickListener(onForumItemListener);
    }


    @Override
    public void onClick(View v) {
        if (v == mHelpBtn) {//求助
            mTabHost.setCurrentTabByTag(TAB_TAG_FOR_HELP);
        } else if (v == mCarAccessoriesBtn) {//汽车用品
            mTabHost.setCurrentTabByTag(TAB_TAG_FOR_SHOP);
        } else if (v == mNearbyBtn) {//附近商家
            startActivity(new Intent(getActivity(), NearbyShopsActivity.class));
        } else if (v == mSignShare) {
            SignShareMenuPow mScheduleMenuPow = new SignShareMenuPow(getActivity());
            mScheduleMenuPow.setIShareListener(this);
            mScheduleMenuPow.show(v);
        } else if (v == seekMoreBtn) {//"为你解忧"更多按钮
            mTabHost.setCurrentTabByTag(TAB_TAG_FOR_HELP);
        } else if (v == storeMoreBtn) {//"为你优选"更多按钮
            startActivity(new Intent(getActivity(), NearbyShopsActivity.class));
        } else if (v == forumMoreBtn) {//"趣味杂谈"更多按钮
            mTabHost.setCurrentTabByTag(TAB_TAG_FOR_BILLION);
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            //在这里做请求操作
            Intent intent = new Intent(getActivity(), HomeSearchActivity.class);
            intent.putExtra(HOME_SEARCH, mEditTxt.getText().toString());
            startActivity(intent);
            return true;
        }
        return false;
    }


    /**
     * 店铺列表适配器
     *
     * @param mShopList
     */
    private void setStoreAdapter(List<ShopParam> mShopList) {
        mStoreAdapter = new AllPowerfulAdapter<ShopParam>(R.layout.service_station_item, mShopList, new AllPowerfulAdapter.OnClickListener<ShopParam>() {
            @Override
            public void setOnClick(BaseViewHolder baseViewHolder, ShopParam shopParam, int position) {
                Intent intent = new Intent(getActivity(), ShopDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt(ClientConstants.FROM, ClientConstants.FROM_NEARBY_STORE);
                bundle.putString(ClientConstants.STORE_ID, shopParam.getStoreId());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        }) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, ShopParam param) {
                super.convert(baseViewHolder, param);
                ImageView shopImg = baseViewHolder.getView(R.id.service_station_item_img);//店铺图片
                Glide.with(getActivity()).load(param.getStoreImageUrl()).into(shopImg);
                baseViewHolder.setText(R.id.service_station_item_title, param.getStoreName());//店铺名字
                baseViewHolder.setText(R.id.service_station_item_location, param.getStoreCity() + param.getStoreAddress());//店铺地址
                baseViewHolder.setText(R.id.service_station_item_distance, param.getDistance());//店铺距离
                LinearLayout tagLayout = baseViewHolder.getView(R.id.service_station_item_tag_layout);
                tagLayout.removeAllViews();
                for (int i = 0; i < param.getTagList().size(); i++) {
                    TextView textView = new TextView(getActivity());
                    textView.setPadding(UIUtils.dip2px(10), 0, UIUtils.dip2px(10), 0);
                    textView.setBackgroundColor(Color.parseColor(param.getTagList().get(i).getTagColor()));
                    textView.setText(param.getTagList().get(i).getTagName());
                    textView.setTextSize(11);
                    textView.setGravity(Gravity.CENTER);
                    textView.setTextColor(Color.WHITE);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, UIUtils.dip2px(22));
                    if (i == 0) {
                        layoutParams.setMargins(0, 0, 0, 0);
                    } else {
                        layoutParams.setMargins(UIUtils.dip2px(12), 0, 0, 0);
                    }
                    tagLayout.addView(textView, layoutParams);
                }

            }
        };
        mStoreListView.setAdapter(mStoreAdapter);
    }


    /**
     * "为你解忧"列表item点击监听
     */
    private OnItemRecyClickListener onSeekItemListener = new OnItemRecyClickListener() {
        @Override
        public void onItemRecyClick(View view, int position) {
            Intent intent = new Intent(getActivity(), HelpDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt(ClientConstants.FROM, ClientConstants.FOR_YOU_MELANCHOLY);
            bundle.putString(SEEK_ID, mSeekList.get(position).getSeekid());
            intent.putExtras(bundle);
            startActivity(intent);
        }
    };


    /**
     * “趣味杂谈"列表item点击监听
     */
    private OnItemRecyClickListener onForumItemListener = new OnItemRecyClickListener() {
        @Override
        public void onItemRecyClick(View view, int position) {
            Intent intent = new Intent(getActivity(), ForumDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString(ClientConstants.FORUM_ID, mForumList.get(position).getForumid());
            intent.putExtras(bundle);
            startActivity(intent);
        }
    };

    //分享按钮
    @Override
    public void OnShare() {
        if (!UMShareAPI.get(getActivity()).isInstall(getActivity(), SHARE_MEDIA.WEIXIN)) {
            ToastUtil.showBelowToast(getActivity(), "您还未安装微信");
            return;
        }
        UMImage image = new UMImage(getActivity(), R.drawable.share_logo);//网络图片
        image.compressStyle = UMImage.CompressStyle.SCALE;//大小压缩，默认为大小压缩，适合普通很大的图
        image.compressStyle = UMImage.CompressStyle.QUALITY;//质量压缩，适合长图的分享
        //压缩格式设置
        image.compressFormat = Bitmap.CompressFormat.PNG;//用户分享透明背景的图片可以设置这种方式，但是qq好友，微信朋友圈，不支持透明背景图片，会变成黑色

        UMWeb web = new UMWeb(ClientConstants.Share_Home_Url);
        web.setTitle("你身边的卡车之家");//标题
        web.setThumb(image);  //缩略图
        web.setDescription("汽车、汽车配件、汽车用品的销售及网上销售，汽车配件的修理服务，车辆信息咨询服务，商务信息咨询服务，广告设计、制作、代理、发布。（依法须经批准的项目，经相关部门批");//描述

        new ShareAction(getActivity()).withMedia(web).
                setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA)
                .setCallback(shareListener).open();
    }


    /**
     * 友盟分享回调
     */
    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtil.showBelowToast(getActivity(), "分享成功");
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Log.i("xiaoyuu", "分享失败  原因：" + t.toString());
            ToastUtil.showBelowToast(getActivity(), "分享失败");
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtil.showBelowToast(getActivity(), "取消了分享");
        }
    };


    /**
     * 获取首页信息
     */
    private void getHomeInfo() {
        NetworkManager.getHomeInfo(lat, lng, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                ToastUtil.logResult("首页", result);
                parseHomeInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                ToastUtil.logError("首页", errorCode, errorDiscription);
            }
        });
    }

    private void parseHomeInfoSuc(String result) {
        HomeBean bean = new Gson().fromJson(result, HomeBean.class);

        //顶部轮播图
        mTopList.clear();
        mTopList.addAll(bean.getData().getTopLunbo());
        List<String> topList = new ArrayList<>();
        for (int i = 0; i < mTopList.size(); i++) {
            topList.add(i, mTopList.get(i).getLunboimg());
        }
        mTopBanner.setImages(topList);
        mTopBanner.start();

        //中间轮播图
        mMiddleList.clear();
        mMiddleList.addAll(bean.getData().getGoodsLunbo());
        List<String> midList = new ArrayList<>();
        for (int i = 0; i < mMiddleList.size(); i++) {
            midList.add(i, mMiddleList.get(i).getLunboimg());
        }
        mMiddleBanner.setImages(midList);
        mMiddleBanner.start();

        //为你解忧
        mSeekList.clear();
        mSeekList.addAll(bean.getData().getSeekList());
        mSeekAdapter.updateList(mSeekList);

        //为你优选
        mStoreList.clear();
        mStoreList.addAll(bean.getData().getStoreList());
        mStoreAdapter.notifyDataSetChanged();

        //趣味杂谈
        mForumList.clear();
        mForumList.addAll(bean.getData().getForumList());
        mForumAdapter.notifyDataSetChanged();
    }

}
